﻿using System;
using ch10.binary;
using ch10.binary.type;

namespace ch10.instance
{
    public static class SigParser
    {
        // name(params)->(results)
        public static (string, FuncType) ParseNameAndSig(string nameAndSig)
        {
            var idxOfLPar = nameAndSig.IndexOf('(', 0);
            var name = nameAndSig[..idxOfLPar];
            var sig = nameAndSig[idxOfLPar..];
            return (name, ParseSig(sig));
        }

        private static FuncType ParseSig(string sig)
        {
            var paramsAndResults = sig.Split("->", 2);
            return new FuncType
            {
                ParamTypes = ParseValTypes(paramsAndResults[0]),
                ResultTypes = ParseValTypes(paramsAndResults[1])
            };
        }

        private static ValType[] ParseValTypes(string list)
        {
            list = list.Trim();
            list = list.Substring(1, list.Length - 1 - 1); // remove ()

            var valTypes = Array.Empty<ValType>();
            foreach (var t in list.Split(','))
            {
                if (t.Trim().Length > 0)
                {
                    Array.Resize(ref valTypes, valTypes.Length + 1);
                    valTypes[^1] = t.Trim() switch
                    {
                        "i32" => ValType.ValTypeI32,
                        "i64" => ValType.ValTypeI64,
                        "f32" => ValType.ValTypeF32,
                        "f64" => ValType.ValTypeF64,
                        _ => valTypes[^1]
                    };
                }
            }

            return valTypes;
        }
    }
}